package com.igame.Utils;

import com.igame.common.service.RedisUserService;
import com.igame.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private RedisUserService redisUserService;
    @Override
    protected void doFilterInternal(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, jakarta.servlet.FilterChain filterChain) throws jakarta.servlet.ServletException, IOException {
        // 获取 Authorization 头
        String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String token = null;

        // 检查 Authorization 头是否存在并且以 Bearer 开头
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            token = authorizationHeader.substring(7);
            try {
                username = jwtUtil.getUsernameFromToken(token);
            } catch (Exception e) {
                System.out.println("JWT Token is invalid");
            }
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = null;

            // 尝试从 Redis 中获取用户信息
            User userFromRedis = redisUserService.getUserFromRedis(username);
            if (userFromRedis != null) {
                // 如果 Redis 中有用户信息，则直接创建 UserDetails
                userDetails = new org.springframework.security.core.userdetails.User(
                        userFromRedis.getUsername(),
                        userFromRedis.getPassword(),
                        new ArrayList<>() // 这里是角色权限列表，假设为空
                );
            } else {
                // 如果 Redis 中没有，尝试从数据库中获取
                userDetails = userDetailsService.loadUserByUsername(username);
                if (userDetails != null) {
                    // 将用户信息存储到 Redis 中
                    User user = new User();
                    BeanUtils.copyProperties(userDetails, user);
                    redisUserService.storeUserInRedis(user);
                }
            }

            // 确保 userDetails 不为 null 再进行 token 验证
            if (userDetails != null && jwtUtil.validateToken(token, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request, response);
    }
}


